package de.justphil.tcg.tcgserver.game.states;

import static de.justphil.tcg.tcgserver.commons.logging.TCGLogging.*;

import org.slf4j.Logger;

import de.justphil.tcg.tcgserver.game.GameManager;
import de.justphil.tcg.tcgserver.game.helpers.GameHelper;
import de.justphil.tcg.tcgserver.game.helpers.GameReporter;
import de.justphil.tcg.tcgserver.websockets.TCGWebSocket;
import de.justphil.tcg.tcgserver.commons.i18n.M;
import de.justphil.tcg.tcgserver.websockets.messages.TCGMessage;

public class WaitingForReconnectingPlayer extends GameState {
	private static final Logger log = logger(WaitingForReconnectingPlayer.class);

	@Override
	protected void progress(GameManager game, TCGWebSocket socket, TCGMessage msg, String data) {
		// Just reconnected player wants to join the game (game-j) again
		boolean connected = GameHelper.registerConnectedPlayerAndNotifyAll(game, socket, msg);
		
		if (connected) {
			game.getTCGAppManageable().signalReconnectedPlayer(game.getPlayerByWebSocket(socket).getPlayerId());
			// TODO: Send the current game state to the player, because it might have changed during his absence.
			// TODO: In the case it's his turn, send him an appropriate notification.
			
			if (game.isReadyToPlay()) {
				log.info("State transition in game '{}': {} -> {}",
						new Object[] { game.getGameId(), this, WaitingForPlayerInteraction.class.getSimpleName() }
				);
				
				game.setState(new WaitingForPlayerInteraction());
				GameReporter.broadcastGameInfo(game, null, M.GAME_CONTINUES);
			}
		}
	}

}
